package com.mlink.vs.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.GroupMembers;
import com.mlink.vs.entity.LocationTraceResult;
import com.mlink.vs.entity.LocationTraceResult1;
import com.mlink.vs.entity.OrgList;
import com.mlink.vs.entity.OrgListResult;
import com.mlink.vs.entity.PiccUser;
import com.mlink.vs.entity.PiccUserLocation;
import com.mlink.vs.entity.PiccUserLocationResult;
import com.mlink.vs.entity.PiccUserOnlineStatus;
import com.mlink.vs.entity.UCResult;
import com.mlink.vs.service.PiccUserLocationService;

import com.mlink.vs.service.PiccUserOnlineStatusService;
import com.mlink.vs.service.PiccUserService;
import com.mlink.vs.sso.BaseAction;
import com.mlink.vs.util.Constants;
import com.mlink.vs.util.StreamUtil;

/**
 * 获取用户列表接口
 * 
 * @author Administrator
 */
public class UserListAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccUserOnlineStatusService piccUserOnlineStatusService;
	@Resource
	PiccUserService piccUserService;

	@Resource
	private PiccUserLocationService piccUserLocationService;

	private JSONArray addOnlineState(JSONArray array, List<PiccUserOnlineStatus> online) throws JSONException {
		for (int i = 0; i < array.length(); i++) {
			JSONObject cell = array.getJSONObject(i);
			String type = cell.getString("type");

			if (type.equals("dep")) {
				JSONArray array1 = cell.getJSONArray("orgList");
				JSONArray arrayNew = addOnlineState(array1, online);
				cell.put("orgList", arrayNew);
			} else {

				String userID = cell.getString("userID");
				cell.put("isOnline", "0");
				for (int j = 0; j < online.size(); j++) {
					PiccUserOnlineStatus po = online.get(j);
					System.out.println("userID=" + userID);
					System.out.println("po.userId=" + po.userId);
					if (po.userId.equals(userID)) {
						cell.put("isOnline", "1");
						break;
					}

				}

			}
			array.put(i, cell);
		}
		return array;
	}

	@Execute(validator = false)
	public String index() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		String keywords = null;
		String TOKEN = null;
		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData != null) {
			keywords = (String) mapData.get("keywords"); // 获取关键字
			TOKEN = (String) mapData.get("token"); // 获取关键字
		}

		rep.setCharacterEncoding("utf-8");
		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000

		if (StringUtils.isBlank(TOKEN)) {
			stsMap.put("sts", "1");
			stsMap.put("msg", "TOKEN不能为空");
			try {
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		try {
			JSONObject body = new JSONObject();
			UCResult resuelt = null;
			body.put("TOKEN", TOKEN);
			body.put("key", keywords);

			resuelt = BaseAction.requeryUC("UAC_USER_GETORG", body);

			if (resuelt.code.equals("1")) {

				JSONArray orgList = resuelt.body.getJSONArray("orgList");
				String isOnline = Constants.USER_STATUS_ONLINE;
		
				List<PiccUserOnlineStatus> PiccUserList = piccUserOnlineStatusService.findIsOnline(isOnline);

				JSONArray orgListNew = addOnlineState(orgList, PiccUserList);
				String aa = orgListNew.toString();
				JSONObject send = new JSONObject();
				send.put("sts", "0");
				send.put("rootList", orgListNew);

				rep.getWriter().println(send.toString());
				rep.getWriter().flush();
				return null;
			} else {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uc 服务器异常 错误码：" + resuelt.code);
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;

			}

		} catch (Exception e) {
			e.printStackTrace();
			stsMap.put("sts", "1");
			stsMap.put("msg", "uc 服务器异常");
			try {
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			return null;

		}
	}

	// 获取在线坐席
	@Execute(validator = false)
	public String getOnlineSeat() {

		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;
		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000
		String userId = (String) mapData.get("uid");
		String token = (String) mapData.get("token");
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uid不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(token)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "token不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			JSONObject body = new JSONObject();
			UCResult resuelt = null;
			body.put("TOKEN", token);
			body.put("userid", userId);

			resuelt = BaseAction.requeryUC("UAC_USER_INFO", body);
			if (resuelt.code.equals("1")) {

				String groupID = resuelt.body.getJSONObject("user").getString("groupID");


				String isOnline = Constants.USER_STATUS_ONLINE;
				String userType1 = Constants.USER_TYPE_SEAT;
				String userType2 = Constants.USER_TYPE_LEADER;
				// 获取本组在线坐席
				List<PiccUserOnlineStatus> PiccUserList = piccUserOnlineStatusService.findIsOnlineOfGroup(isOnline, userType1,
						userType2, groupID);
				List list = new ArrayList();
				if (null != PiccUserList && PiccUserList.size() > 0) {
					stsMap.put("sts", "0");
					for (int i = 0; i < PiccUserList.size(); i++) {
						String userId2 = PiccUserList.get(i).userId;
						list.add(userId2);
					}
					stsMap.put("list", list);
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
				} else {
					stsMap.put("sts", "2");
					stsMap.put("list", list);
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
				}

			} else {
				stsMap.put("sts", "3");
				stsMap.put("msg", "未获取到用户信息");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}

		} catch (IOException | JSONException e) {
			e.printStackTrace();
		}

		return null;

	}
//
//	// 获取在线
//	@Execute(validator = false)
//	public String getOnlinePerson() {
//
//		Gson gson = new Gson();
//		StringBuffer indata = StreamUtil.getRequestBody(req);
//		Map stsMap = new HashMap<String, String>();
//
//		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
//		if (mapData == null)
//			return null;
//		if (BaseAction.checkToken(indata, rep) == false)
//			return null; // 验证token是否有效 无效直接返回错误码-1000
//		String userId = (String) mapData.get("uid");
//		String token = (String) mapData.get("token");
//		// 获取用户组id
//
//		try {
//			rep.setCharacterEncoding("utf-8");
//			if (StringUtils.isBlank(userId)) {
//				stsMap.put("sts", "1");
//				stsMap.put("msg", "uid不能为空");
//				rep.getWriter().println(gson.toJson(stsMap));
//				rep.getWriter().flush();
//				return null;
//			}
//			if (StringUtils.isBlank(token)) {
//				stsMap.put("sts", "1");
//				stsMap.put("msg", "token不能为空");
//				rep.getWriter().println(gson.toJson(stsMap));
//				rep.getWriter().flush();
//				return null;
//			}
//			JSONObject body = new JSONObject();
//			UCResult resuelt = null;
//			body.put("TOKEN", token);
//			body.put("userid", userId);
//
//			resuelt = BaseAction.requeryUC("UAC_USER_INFO", body);
//			if (resuelt.code.equals("1")) {
//
//				String groupID = resuelt.body.getJSONObject("user").getString("groupID");
//				String isOnline = Constants.USER_STATUS_ONLINE;
//				List<PiccUserOnlineStatus> PiccUserList = piccUserOnlineStatusService.findIsOnlinePerson(isOnline,
//						groupID);
//				List list = new ArrayList();
//				if (null != PiccUserList && PiccUserList.size() > 0) {
//					stsMap.put("sts", "0");
//					for (int i = 0; i < PiccUserList.size(); i++) {
//						String userId2 = PiccUserList.get(i).userId;
//						list.add(userId2);
//					}
//					stsMap.put("list", list);
//					rep.getWriter().println(gson.toJson(stsMap));
//					rep.getWriter().flush();
//				} else {
//					stsMap.put("sts", "2");
//					stsMap.put("list", list);
//					rep.getWriter().println(gson.toJson(stsMap));
//					rep.getWriter().flush();
//				}
//			} else {
//				stsMap.put("sts", "3");
//				stsMap.put("msg", "未获取到用户信息");
//				rep.getWriter().println(gson.toJson(stsMap));
//				rep.getWriter().flush();
//			}
//		} catch (IOException | JSONException e) {
//			e.printStackTrace();
//		}
//
//		return null;
//
//	}

	// 获取在线坐席数
	@Execute(validator = false)
	public String getOnlineSeatNum() {

		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;
		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000
		String userId = (String) mapData.get("uid");
		String token = (String) mapData.get("token");
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uid不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(token)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "token不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			JSONObject body = new JSONObject();
			UCResult resuelt = null;
			body.put("TOKEN", token);
			body.put("userid", userId);

			resuelt = BaseAction.requeryUC("UAC_USER_INFO", body);
			if (resuelt.code.equals("1")) {

				String groupID = resuelt.body.getJSONObject("user").getString("groupID");

				String isOnline = Constants.USER_STATUS_ONLINE;
				String userType1 = Constants.USER_TYPE_SEAT;
				String userType2 = Constants.USER_TYPE_LEADER;
				int totalCount = piccUserOnlineStatusService.findIsOnlineCount(isOnline, userType1, userType2,groupID);
				stsMap.put("sts", "0");
				stsMap.put("totalCount", totalCount);
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}
		} catch (IOException | JSONException e) {
			e.printStackTrace();
		}

		return null;

	}

	// 获取本组坐席列表接口
	@Execute(validator = false)
	public String getMembersOfGroup() {
		Gson gson = new Gson();

		StringBuffer indata = StreamUtil.getRequestBody(req);
		String userId = null;
		String token = null;
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);

		Map<String, String> stsMap = new HashMap<String, String>();

		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000

		if (mapData != null) {
			userId = (String) mapData.get("userId"); // 获取关键字
			token = (String) mapData.get("token"); // token
		}

		rep.setCharacterEncoding("utf-8");
		try {
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");

				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(token)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");

				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000
		try {
			JSONObject body = new JSONObject();
			UCResult resuelt = null;

			body.put("TOKEN", token);

			resuelt = BaseAction.requeryUC("UAC_USER_GETMEMBERSOFGROUP", body);

			if (resuelt.code.equals("1")) {

				JSONArray users = resuelt.body.getJSONArray("users");
				JSONObject result = new JSONObject();
				result.put("sts", "0");
				result.put("list", users);
				// String aa = resBody.toString();

				rep.getWriter().println(result.toString());
				rep.getWriter().flush();
				return null;
			} else {
				stsMap.put("sts", "1");
				stsMap.put("msg", "uc 服务器异常 错误码：" + resuelt.code);
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 轨迹查询
	@Execute(validator = false)
	public String getLocationTrace() {
		Gson gson = new Gson();

		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);

		Map<String, String> stsMap = new HashMap<String, String>();
		String userId = null;
		String start = null;
		String end = null;

		if (mapData != null) {
			userId = (String) mapData.get("userId"); // 获取关键字
			start = (String) mapData.get("start"); // 起始时间
			end = (String) mapData.get("end"); // 结束时间
		}

		try {

			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "start不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			if (StringUtils.isBlank(start)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "start不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			if (StringUtils.isBlank(end)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "end不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			//////
			List<PiccUserLocation> list;
			list = piccUserLocationService.findAllbyId(userId, start, end);
			LocationTraceResult1 gmr = new LocationTraceResult1();
			gmr.sts = "0";
			gmr.list = list;

			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(gmr));
			rep.getWriter().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获取用户 最新经纬度
	@Execute(validator = false)
	public String getUserLocation() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		List<String> mapData = gson.fromJson(indata.toString(), List.class);
		Map<String, String> stsMap = new HashMap<String, String>();
		try {

			rep.setCharacterEncoding("utf-8");
			if (mapData.size() <= 0) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "请传数据");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			List<PiccUserLocationResult> list = new ArrayList<PiccUserLocationResult>();

			for (int i = 0; i < mapData.size(); i++) {
				PiccUserLocationResult pl = piccUserLocationService.findOneById(mapData.get(i));
				if (pl != null)
					list.add(pl);
			}
			LocationTraceResult gmr = new LocationTraceResult();
			gmr.sts = "0";
			gmr.list = list;
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(gmr));
			rep.getWriter().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}